package com.example.huanhang.changzhouapp.activity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.example.huanhang.changzhouapp.R;
import com.example.huanhang.changzhouapp.adapter.ListAllAdapter;
import com.example.huanhang.changzhouapp.base.BaseBackActivity;
import com.example.huanhang.changzhouapp.bean.ListInfo;
import com.example.huanhang.changzhouapp.bean.User;
import com.example.huanhang.changzhouapp.util.DateUtils;
import com.example.huanhang.changzhouapp.util.ThreadUtil;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import static com.example.huanhang.changzhouapp.util.ConstantUtils.IS_NOTICE_PERMISSIONS;


/**
 * @author lei
 * @desc 公告页面
 * @date 2018/8/27 0027 -- 上午 11:07.
 * 个人博客站: http://www.bestlei.top
 */
public class NoticeActivity extends BaseBackActivity implements OnRefreshListener, View.OnClickListener {

    List<User> nameList = new ArrayList<User>();
    private TextView mTvRen;
    private TextView mTvDate;
    private RecyclerView mInRecycleview;
    private SmartRefreshLayout mInRefresh;
    private ListAllAdapter mAdapter;
    private List<ListInfo> mList = new ArrayList<>();
    private AppCompatTextView mTvTitle;
    private FloatingActionButton mMenuItem;
    private FloatingActionMenu mMenu;
    private Handler workJBHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case 0:
                    //失败
                    dismissWaitDialog();
                    toast("查询失败");
                    break;
                case 1:
                    //成功
                    dismissWaitDialog();
                    mAdapter.notifyDataSetChanged();
                    break;
                case 2:
                    dismissWaitDialog();
                    String[] mItems = new String[nameList.size() + 1];
                    for (int i = 0; i < nameList.size() + 1; i++) {
                        if (i < nameList.size()) {
                            mItems[i] = nameList.get(i).getName();
                        } else {
                            mItems[i] = "全部人员";
                        }

                    }
                    new AlertDialog.Builder(NoticeActivity.this).setTitle("选取人员")
                            .setItems(mItems, (dialog, which) -> {
                                mTvRen.setText(mItems[which]);
                                if ("全部人员".equals(mItems[which])) {
                                    initNoticeData();
                                } else {
                                    initSelectName(mItems[which]);
                                }
                            }).show();
                    break;
                case 3:
                    //选取人员后
                    dismissWaitDialog();
                    mAdapter.notifyDataSetChanged();
                    break;
                case 4:
                    //选取日期后
                    dismissWaitDialog();
                    mAdapter.notifyDataSetChanged();
                    break;
                case 5:
                    //选取日期后无数据
                    dismissWaitDialog();
                    mAdapter.setEmptyView(getEmptyView());
                    mAdapter.notifyDataSetChanged();
                    break;
            }
            return false;
        }
    });
    private String mUserPermissions;

    private void initSelectName(String name) {
        showWaitDialog("请稍后...");
        if (mList.size() != 0) {
            mList.clear();
        }
        ThreadUtil.runOnBackThread(() -> {
            String sql = "SELECT * FROM gonggao WHERE lccb_name='" + name + "' ORDER BY lccb_time DESC";
            try {
                ResultSet result = ThreadUtil.result(sql);
                while (result.next()) {
                    ListInfo listInfo = new ListInfo();
                    listInfo.setName(result.getString("lccb_name"));
                    listInfo.setDate(result.getString("lccb_time"));
                    listInfo.setTitle(result.getString("lccb_title"));
                    listInfo.setContent(result.getString("lccb_content"));
                    mList.add(listInfo);
                }

                if (mList.size() == 0) {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(0));
                } else {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(3));
                }
                result.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_notice;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mTvRen = (TextView) findViewById(R.id.tv_ren);
        mTvDate = (TextView) findViewById(R.id.tv_date);
        mMenuItem = (FloatingActionButton) findViewById(R.id.menu_item);
        mMenu = (FloatingActionMenu) findViewById(R.id.menu);
        mTvRen.setOnClickListener(this);
        mTvDate.setOnClickListener(this);
        mMenuItem.setOnClickListener(this);
        mInRecycleview = (RecyclerView) findViewById(R.id.in_recycleview);
        mInRefresh = (SmartRefreshLayout) findViewById(R.id.in_refresh);
        mTvTitle = (AppCompatTextView) findViewById(R.id.tv_title);
        ImmersionBar.with(this).statusBarColor(R.color.title).init();
    }

    @Override
    public void initData() {
        mTvTitle.setText("通知公告");
        mInRefresh.setEnableAutoLoadMore(false);
        mInRefresh.setOnRefreshListener(this);
        mInRefresh.setRefreshHeader(new ClassicsHeader(this));
        setAdapterData();
        mInRecycleview.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ListAllAdapter(R.layout.item_list_layout, mList);
        mAdapter.setEmptyView(getEmptyView());
        adapterClickInfo();
        mInRecycleview.setAdapter(mAdapter);
    }

    private void setAdapterData() {
        initNoticeData();
    }

    private View getEmptyView() {
        return LayoutInflater.from(this).inflate(R.layout.empty_layout, null);
    }

    private void adapterClickInfo() {
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            ListInfo listInfo = mList.get(position);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            LayoutInflater inflater = LayoutInflater.from(this);
            View v = inflater.inflate(R.layout.dialog_layout, null);
            TextView title = v.findViewById(R.id.title);
            TextView date = v.findViewById(R.id.date);
            TextView name = v.findViewById(R.id.name);
            TextView content = v.findViewById(R.id.content);
            TextView tvok = v.findViewById(R.id.tvok);
            title.setText(listInfo.getTitle());
            date.setText(listInfo.getDate());
            name.setText(listInfo.getName());
            content.setText(listInfo.getContent());
            final Dialog dialog = builder.create();
            dialog.show();
            dialog.getWindow().setContentView(v);
            tvok.setOnClickListener(v1 -> dialog.dismiss());
        });

    }

    private void initNoticeData() {
        showWaitDialog("查询中...");
        if (mList.size() != 0) {
            mList.clear();
        }
        ThreadUtil.runOnBackThread(() -> {
            String sql = "SELECT * FROM gonggao ORDER BY lccb_time DESC";
            try {
                ResultSet result = ThreadUtil.result(sql);
                while (result.next()) {
                    ListInfo listInfo = new ListInfo();
                    listInfo.setName(result.getString("lccb_name"));
                    listInfo.setDate(result.getString("lccb_time"));
                    listInfo.setTitle(result.getString("lccb_title"));
                    listInfo.setContent(result.getString("lccb_content"));
                    mList.add(listInfo);
                }

                if (mList.size() == 0) {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(0));
                } else {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(1));
                }
                result.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        initNoticeData();
        mTvDate.setText("按日期");
        mTvRen.setText("按发布人");
        mInRefresh.finishRefresh();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_ren:
                initNameData();
                mTvDate.setText("按日期");
                break;
            case R.id.tv_date:
                mTvRen.setText("按发布人");
                new DatePickerDialog(NoticeActivity.this, 0, (view, year, month, dayOfMonth) -> {
                    String mouth =DateUtils. isOneLengthMouth(month+1);
                    String day = DateUtils.isOneLengthDay(dayOfMonth);
                    mTvDate.setText(year + "-" + mouth + "-" + day);
                    initSelectDate(mTvDate.getText().toString());
                }, DateUtils.getCurrentYear(),DateUtils.getCurrentMonth()-1,DateUtils.getCurrentDay())
                        .show();
                break;
            case R.id.menu_item:
                if (IS_NOTICE_PERMISSIONS.equals(mUserPermissions)) {
                    //  0  有新建通知公告的权限
                    Intent intent = new Intent(NoticeActivity.this, CreatNoticeActivity.class);
                    startActivity(intent);
                    mMenu.close(true);

                } else {
                    toast("无权限");
                }
                break;
        }
    }

    private void initSelectDate(String date) {
        showWaitDialog("查询中...");
        if (mList.size() != 0) {
            mList.clear();
        }
        Log.e("ASD", "initSelectDate: "+date );
        ThreadUtil.runOnBackThread(() -> {
            String sql = "SELECT * FROM gonggao WHERE LEFT(lccb_time,10)='" + date + "' ORDER BY lccb_time DESC";
            try {
                ResultSet result = ThreadUtil.result(sql);
                while (result.next()) {
                    ListInfo listInfo = new ListInfo();
                    listInfo.setName(result.getString("lccb_name"));
                    listInfo.setDate(result.getString("lccb_time"));
                    listInfo.setTitle(result.getString("lccb_title"));
                    listInfo.setContent(result.getString("lccb_content"));
                    mList.add(listInfo);
                }

                if (mList.size() == 0) {
                    //失败
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(5));
                } else {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(4));
                }
                result.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void initNameData() {
        showWaitDialog("请稍后...");
        if (nameList.size() != 0) {
            nameList.clear();
        }
        ThreadUtil.runOnBackThread(() -> {
            String sql = "SELECT distinct  lccb_name FROM gonggao";
            try {
                ResultSet result = ThreadUtil.result(sql);
                while (result.next()) {
                    User user = new User();
                    user.setName(result.getString("lccb_name"));
                    nameList.add(user);
                }
                if (nameList.size() == 0) {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(0));
                } else {
                    workJBHandler.sendMessage(workJBHandler.obtainMessage(2));
                }
                result.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(User user) {
        mUserPermissions = user.getPermissions();

    }
}
